package com.echo.neocommunity.event;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.echo.neocommunity.pojo.Event;
import com.echo.neocommunity.pojo.Message;
import com.echo.neocommunity.service.MessageService;
import com.echo.neocommunity.service.impl.MessageServiceImpl;
import com.echo.neocommunity.utils.CommunityConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class EventConsumer {
    private final static Logger logger= LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    private MessageServiceImpl messageService;


    @KafkaListener(topics = {CommunityConstant.TOPIC_COMMENT,CommunityConstant.TOPIC_LIKE,CommunityConstant.TOPIC_FOLLOW})
    public void handlerCommentMessage(ConsumerRecord record){
        if(record==null || record.value()==null){
            logger.error("消息的内容为空！");
            return;
        }
        Event event = JSON.parseObject(record.value().toString(), Event.class);
        if(event==null){
            logger.error("消息的内容为空！");
            return;
        }
        Message message=new Message();
        message.setFromId(1);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());
        Map<String,Object> content=new HashMap<>();
        content.put("userId",event.getUserId());
        content.put("entityType",event.getEntityType());
        content.put("entityId",event.getEntityId());
        Map<String, Object> data = event.getData();
        if(!data.isEmpty()){
            for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
                data.put(stringObjectEntry.getKey(),stringObjectEntry.getValue());
            }
        }
        message.setContent(JSON.toJSONString(event));
        messageService.save(message);
    }

}
